using System.Timers;
using CoreGraphics;
using Foundation;
using mb;
using mb.iOS;
using Masonry;
using MyExtensions;
using UIKit;

namespace libmp
{
    public class VCRegisterController : UIViewController
    {
        static ILog logger = mb.ServiceLocator.Instance.Get<ILog>();
        VCSetting setting;

        public VCRegisterController(VCSetting vcSetting)
        {
            TabBarItem = new UITabBarItem("设置", null, 0);
            setting = vcSetting;
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            CreateView();
        }

        private void CreateView()
        {

            var bkView = new UIView() { BackgroundColor = Util.MainBKColor };
            bkView.SetParent(View).MakeConstraints(m =>
            {
                m.Top.EqualTo(this.TopLayoutGuideBottom());
                m.Left.Right.Bottom.EqualTo(View);
            });
            var mainView = new UIView();
            mainView.SetParent(View);
            mainView.MakeConstraints(m =>
            {
                m.Left.EqualTo(View);
                m.Right.EqualTo(View);
                m.Top.EqualTo(this.TopLayoutGuideBottom());
                m.Bottom.EqualTo(View);
            });
            createTopBar(mainView);
            createContents(mainView);
            createButton(mainView);
        }

        private void createTopBar(UIView mainView)
        {
            var btnPicWidth = 15;
            var btnPicHeight = 15;
            var topBarView = new UIView();
            topBarView.BackgroundColor = UIColor.FromRGB(251, 114, 153);
            topBarView.SetParent(mainView);
            topBarView.MakeConstraints(m =>
            {
                m.Left.EqualTo(View);
                m.Right.EqualTo(View);
                m.Top.EqualTo(this.TopLayoutGuideBottom());
                m.Height.EqualTo(NSObject.FromObject(48));
            });

            var topBarLeftView = new UIView();
            topBarLeftView.SetParent(topBarView);
            topBarLeftView.MakeConstraints(m =>
            {
                m.Left.EqualTo(NSObject.FromObject(10));
                m.Top.EqualTo(topBarView);
                m.Bottom.EqualTo(topBarView);
                m.Width.EqualTo(NSObject.FromObject((View.Bounds.Width - 20) / 3));
            });

            var leftButton1 = new UIButton();
            leftButton1.Frame = new CGRect(0, 14, btnPicWidth + 30, btnPicHeight + 5);
            leftButton1.SetParent(topBarLeftView);
            var leftButton1ImageView = new UIImageView();
            var imgoperationArrow1 = UIImage.FromFile($"{App.HotStorageRoot}/res/user/Fanhui.png");
            leftButton1ImageView.Image = new UIImage(imgoperationArrow1.CGImage, 2, UIImageOrientation.Up);
            leftButton1ImageView.SetParent(leftButton1);
            leftButton1ImageView.MakeConstraints(m =>
            {
                m.CenterY.EqualTo(leftButton1.CenterY());
                m.Left.EqualTo(NSObject.FromObject(5));
                m.Height.EqualTo(NSObject.FromObject(btnPicHeight));
                m.Width.EqualTo(NSObject.FromObject(btnPicWidth / 2));
            });
            var leftButton2Label = new UILabel();
            leftButton2Label.Text = "返回";
            leftButton2Label.Font = UIFont.SystemFontOfSize(12);
            leftButton2Label.SetParent(leftButton1);
            leftButton2Label.TextColor = UIColor.White;
            leftButton2Label.MakeConstraints(m =>
            {
                m.CenterY.EqualTo(leftButton1.CenterY());
                m.Left.EqualTo(NSObject.FromObject(20));
                m.Height.EqualTo(NSObject.FromObject(btnPicHeight));
                m.Width.EqualTo(NSObject.FromObject(btnPicWidth + 20));
            });
            leftButton1.TouchUpInside += (s, e) =>
            {
                logger.Log("返回====>");
                AppDelegate.Instance.NavController.PopViewController(false);
            };

            var topBarMiddleView = new UIView();
            topBarMiddleView.SetParent(topBarView);
            topBarMiddleView.MakeConstraints(m =>
            {
                m.Left.EqualTo(topBarLeftView.Right());
                m.Top.EqualTo(topBarView);
                m.Bottom.EqualTo(topBarView);
                m.Width.EqualTo(NSObject.FromObject((View.Bounds.Width - 20) / 3));
            });

            var middleLabel = new UILabel();
            middleLabel.Text = "注册账号";
            middleLabel.Font = UIFont.BoldSystemFontOfSize(18);
            middleLabel.SetParent(topBarMiddleView);
            middleLabel.TextColor = UIColor.White;
            middleLabel.MakeConstraints(m =>
            {
                m.CenterY.EqualTo(topBarMiddleView.CenterY());
                m.CenterX.EqualTo(topBarMiddleView.CenterX());
            });

            var topBarRightView = new UIView();
            topBarRightView.SetParent(topBarView);
            topBarRightView.MakeConstraints(m =>
            {
                m.Left.EqualTo(topBarMiddleView.Right());
                m.Top.EqualTo(topBarView);
                m.Bottom.EqualTo(topBarView);
                m.Width.EqualTo(NSObject.FromObject((View.Bounds.Width - 20) / 3));
            });
        }
        UILabel msgLabel = new UILabel();
        private void createContents(UIView mainView)
        {
            var msgLabelView = new UIView();
            msgLabelView.SetParent(mainView);
            msgLabelView.MakeConstraints(m =>
            {
                m.Left.EqualTo(View);
                m.Right.EqualTo(View);
                m.Top.EqualTo(NSObject.FromObject(55));
                m.Height.EqualTo(NSObject.FromObject(20));
            });

            msgLabel.SetParent(msgLabelView);
            msgLabel.TextAlignment = UITextAlignment.Center;
            msgLabel.Frame = new CGRect(0, 0, View.Bounds.Width, 15);

            var EditTextView = new UIView();
            EditTextView.SetParent(mainView);
            EditTextView.MakeConstraints(m =>
            {
                m.Left.EqualTo(View);
                m.Right.EqualTo(View);
                m.Top.EqualTo(NSObject.FromObject(75));
                m.Height.EqualTo(NSObject.FromObject(220));
            });

            createTextField(EditTextView, "昵称", nickNameTextField, "请输入用户昵称", 0, false);
            createTextField(EditTextView, "＋86", telphoneTextField, "请输入常用手机号", 60, true);
            createTextField(EditTextView, "验证码", verificationTextField, "请输入验证码", 108.5f, false);
            createTextField(EditTextView, "密码", passwordTextField, "6~16个字符，区分大小写", 168.5f, false);
        }
        UITextField nickNameTextField = new UITextField();
        UITextField telphoneTextField = new UITextField();
        UITextField verificationTextField = new UITextField();
        UITextField passwordTextField = new UITextField();
        private UILabel secondLabel = new UILabel();
        private int second = 60;
        private void createTextField(UIView EditTextView, string labelString, UITextField textFieldName, string placeholderString, float topSize, bool ifTelphone)
        {
            var oneTextFieldViewHeight = 48;
            var textFieldWidth = View.Bounds.Width;
            var oneTextFieldView = new UIView();
            oneTextFieldView.BackgroundColor = UIColor.White;
            oneTextFieldView.SetParent(EditTextView);
            oneTextFieldView.MakeConstraints(m =>
            {
                m.Top.EqualTo(NSObject.FromObject(topSize));
                m.Left.EqualTo(NSObject.FromObject(0));
                m.Height.EqualTo(NSObject.FromObject(oneTextFieldViewHeight));
                m.Right.EqualTo(NSObject.FromObject(0));
            });

            var textFieldUILabel = new UILabel();
            textFieldUILabel.Text = labelString;
            textFieldUILabel.Font = UIFont.SystemFontOfSize(14);
            textFieldUILabel.TextColor = UIColor.FromRGB(33, 33, 33);
            textFieldUILabel.SetParent(oneTextFieldView);
            textFieldUILabel.MakeConstraints(m =>
            {
                m.CenterY.EqualTo(oneTextFieldView.CenterY());
                m.Left.EqualTo(NSObject.FromObject(20));
                m.Height.EqualTo(NSObject.FromObject(15));
                m.Width.EqualTo(NSObject.FromObject(80));
            });

            textFieldName.SetParent(oneTextFieldView);
            textFieldName.MakeConstraints(m =>
            {
                m.CenterY.EqualTo(oneTextFieldView.CenterY());
                m.Left.EqualTo(NSObject.FromObject(100));
                m.Height.EqualTo(NSObject.FromObject(20));
                m.Width.EqualTo(NSObject.FromObject(textFieldWidth - 200));
            });
            textFieldName.Placeholder = placeholderString;
            textFieldName.Font = UIFont.SystemFontOfSize(12);
            textFieldName.TextColor = UIColor.FromRGB(33, 33, 33);
            textFieldName.AutocapitalizationType = UITextAutocapitalizationType.None;
            textFieldName.AutocorrectionType = UITextAutocorrectionType.No;
            textFieldName.ReturnKeyType = UIReturnKeyType.Done;
            textFieldName.Delegate = new MyUITextFieldDelegate()
            {
                MyShouldReturn = (tf) =>
                {
                    tf.ResignFirstResponder();
                    return true;
                }
            };
            if (ifTelphone)
            {
                var verificationView = new UIView();
                verificationView.SetParent(oneTextFieldView);
                verificationView.MakeConstraints(m =>
                {
                    m.Top.EqualTo(NSObject.FromObject(12));
                    m.Right.EqualTo(NSObject.FromObject(0));
                    m.Height.EqualTo(NSObject.FromObject(24));
                    m.Width.EqualTo(NSObject.FromObject(100));
                });
                var verificationViewLeft = new UIView();
                verificationViewLeft.SetParent(verificationView);
                verificationViewLeft.BackgroundColor = UIColor.FromRGB(238, 238, 238);
                verificationViewLeft.MakeConstraints(m =>
                {
                    m.Top.EqualTo(verificationView);
                    m.Left.EqualTo(NSObject.FromObject(0));
                    m.Bottom.EqualTo(verificationView);
                    m.Width.EqualTo(NSObject.FromObject(0.5));
                });
                var verificationViewRight = new UIView();
                verificationViewRight.SetParent(verificationView);
                verificationViewRight.MakeConstraints(m =>
                {
                    m.Top.EqualTo(verificationView);
                    m.Left.EqualTo(verificationViewLeft.Right());
                    m.Bottom.EqualTo(verificationView);
                    m.Right.EqualTo(verificationView);
                });

                secondLabel.SetParent(verificationViewRight);
                secondLabel.TextAlignment = UITextAlignment.Center;
                secondLabel.Frame = new CGRect(0, 0, 99.5, 24);
                secondLabel.Text = second + "s";
                secondLabel.TextColor = UIColor.Red;
                secondLabel.Font = UIFont.SystemFontOfSize(14);
                secondLabel.Alpha = 0;

                var verificationButton = new UIButton(UIButtonType.System);
                verificationButton.Frame = new CGRect(0, 0, 99.5, 24);
                verificationButton.SetParent(verificationViewRight);
                var verificationBtnLabel = new UILabel();
                verificationBtnLabel.Text = "获取验证码";
                verificationBtnLabel.SetParent(verificationButton);
                verificationBtnLabel.TextAlignment = UITextAlignment.Center;
                verificationBtnLabel.Font = UIFont.SystemFontOfSize(12);
                verificationBtnLabel.TextColor = UIColor.FromRGB(39, 124, 240);
                verificationBtnLabel.MakeConstraints(m =>
                {
                    m.Left.EqualTo(NSObject.FromObject(0));
                    m.Top.EqualTo(NSObject.FromObject(0));
                    m.Right.EqualTo(NSObject.FromObject(0));
                    m.Bottom.EqualTo(NSObject.FromObject(0));
                });
                verificationButton.TouchUpInside += (s, e) =>
                {
                    logger.Log("获取手机验证码");
                    initWrongMsg();
                    if (verifyTelephone() == true)
                    {
                        string telphoneString = telphoneTextField.Text;
                        setting.UserRegister(telphoneString, "", "", "", "", (requestInfo) =>
                        {
                            var res = showMsgView(requestInfo);
                            if (res)
                            {
                                showVerifySecond(verificationButton);
                            }
                        });
                    }

                };
            }
        }
        private void createButton(UIView mainView)
        {
            var bWidth = View.Bounds.Width - 50;
            var buttonView = new UIView();
            buttonView.SetParent(mainView);
            buttonView.MakeConstraints(m =>
            {
                m.Width.EqualTo(NSObject.FromObject(bWidth));
                m.CenterX.EqualTo(View.CenterX());
                m.Top.EqualTo(NSObject.FromObject(310));
                m.Height.EqualTo(NSObject.FromObject(50));
            });

            var agreementView = new UIView();
            agreementView.SetParent(mainView);
            agreementView.MakeConstraints(m =>
            {
                m.Width.EqualTo(NSObject.FromObject(View.Bounds.Width));
                m.CenterX.EqualTo(View.CenterX());
                m.Top.EqualTo(NSObject.FromObject(390));
                m.Height.EqualTo(NSObject.FromObject(25));
            });
            createAgreement(agreementView);

            var registerButonView = new UIView();
            registerButonView.SetParent(buttonView);
            registerButonView.BackgroundColor = UIColor.FromRGB(251, 114, 153);
            registerButonView.MakeConstraints(m =>
            {
                m.Left.EqualTo(NSObject.FromObject(0));
                m.Top.EqualTo(NSObject.FromObject(0));
                m.Width.EqualTo(NSObject.FromObject(bWidth));
                m.Height.EqualTo(NSObject.FromObject(50));
            });
            registerButonView.Layer.CornerRadius = 6;
            registerButonView.ClipsToBounds = true;
            registerButonView.Layer.BorderWidth = 0;
            var registerButton = new UIButton();
            registerButton.Frame = new CGRect(0, 0, bWidth, 50);
            registerButton.SetParent(registerButonView);
            var registerLabel = new UILabel();
            registerLabel.Text = "立即注册";
            registerLabel.TextColor = UIColor.White;
            registerLabel.SetParent(registerButton);
            registerLabel.MakeConstraints(m =>
            {
                m.CenterY.EqualTo(registerButonView.CenterY());
                m.CenterX.EqualTo(registerButonView.CenterX());
                m.Height.EqualTo(NSObject.FromObject(20));
                m.Width.EqualTo(NSObject.FromObject(70));
            });
            registerButton.TouchUpInside += (s, e) =>
            {
                logger.Log("注册操作");
                doRegister();
            };
        }
        private void createAgreement(UIView agreementView)
        {
            var agreementLabel = new UILabel();
            agreementLabel.Text = "点击”立即注册“按钮,即表示同意";
            agreementLabel.TextAlignment = UITextAlignment.Right;
            agreementLabel.TextColor = UIColor.FromRGB(33, 33, 33);
            agreementLabel.Font = UIFont.SystemFontOfSize(12);
            agreementLabel.SetParent(agreementView);
            agreementLabel.MakeConstraints(m =>
            {
                m.Left.EqualTo(agreementView);
                m.Top.EqualTo(agreementView);
                m.Width.EqualTo(NSObject.FromObject(View.Bounds.Width * 2 / 3));
                m.Bottom.EqualTo(agreementView);
            });

            var agreementButton = new UIButton(UIButtonType.System);
            //agreementButton.Frame = new CGRect(230, 0, 70, 24);
            agreementButton.SetParent(agreementView);
            // agreementButton.BackgroundColor = UIColor.Green;
            agreementButton.MakeConstraints(m =>
            {
                m.Width.EqualTo(NSObject.FromObject(View.Bounds.Width / 3 - 15));
                m.Top.EqualTo(NSObject.FromObject(0));
                m.Left.EqualTo(NSObject.FromObject(View.Bounds.Width * 2 / 3 + 5));
                m.Height.EqualTo(NSObject.FromObject(20));
            });

            var agreementBtnLabel = new UILabel();
            agreementBtnLabel.Text = "注册协议";
            agreementBtnLabel.SetParent(agreementView);
            agreementBtnLabel.TextAlignment = UITextAlignment.Left;
            // agreementBtnLabel.BackgroundColor = UIColor.Yellow;
            agreementBtnLabel.Font = UIFont.SystemFontOfSize(12);
            agreementBtnLabel.TextColor = UIColor.FromRGB(39, 124, 240);
            agreementBtnLabel.MakeConstraints(m =>
            {
                m.Width.EqualTo(NSObject.FromObject(View.Bounds.Width / 3 - 5));
                m.Top.EqualTo(NSObject.FromObject(0));
                m.Left.EqualTo(NSObject.FromObject(View.Bounds.Width * 2 / 3 + 5));
                m.Height.EqualTo(NSObject.FromObject(25));
            });

            agreementButton.TouchUpInside += (s, e) =>
            {
                logger.Log("同意注册");
            };
        }
        private void doRegister()
        {
            bool ifCanSubmit = true;
            initWrongMsg();
            string nickNameString = nickNameTextField.Text;
            string telphoneString = telphoneTextField.Text;
            string VerificationString = verificationTextField.Text;
            string passwordString = passwordTextField.Text;

            if (nickNameString.Length < 1)
            {
                msgLabel.Text = "昵称不能为空";
                msgLabel.TextColor = UIColor.Red;
                ifCanSubmit = false;
            }
            else if (verifyTelephone() == false)
            {
                ifCanSubmit = false;
            }
            else if (VerificationString.Length < 1)
            {
                msgLabel.Text = "验证码错误";
                msgLabel.TextColor = UIColor.Red;
                ifCanSubmit = false;
            }
            else if (passwordString.Length < 6)
            {
                msgLabel.Text = "密码不能低于6位";
                msgLabel.TextColor = UIColor.Red;
                ifCanSubmit = false;
            }
            else if (passwordString.Length > 16)
            {
                msgLabel.Text = "密码不能大于16位";
                msgLabel.TextColor = UIColor.Red;
                ifCanSubmit = false;
            }

            if (ifCanSubmit)
            {
                logger.Log("验证通过，执行注册操作····");
                setting.UserRegister(telphoneString, nickNameString, VerificationString, "", passwordString, (requestInfo) =>
                {
                    bool res = showMsgView(requestInfo);
                    if (res)
                    {
                        User.me.phone = telphoneString;
                        User.me.name = nickNameString;
                        User.me.Notify("register");
                        var second = 5;
                        var testTimer = new Timer() { Interval = 1000, Enabled = true };
                        testTimer.Elapsed += (object sender, System.Timers.ElapsedEventArgs ee) =>
                        {
                            if (second < 1)
                            {
                                (sender as Timer).Stop();
                            }
                            this.InvokeOnMainThread(() =>
                            {
                                // VCSetting.shadowView.Alpha = 0;
                                AppDelegate.Instance.NavController.PopViewController(false);
                                setting.openLoginController();
                                second--;
                            });
                        };

                    }
                });

            }
        }
        private void showVerifySecond(UIButton verificationButton)
        {
            secondLabel.Alpha = 1;
            verificationButton.Alpha = 0;
            secondLabel.Text = second + "s";
            second--;
            var testTimer = new Timer() { Interval = 1000, Enabled = true };
            testTimer.Elapsed += (object sender, System.Timers.ElapsedEventArgs e) =>
            {
                if (second < 1)
                {
                    (sender as Timer).Stop();
                }
                this.InvokeOnMainThread(() =>
                {
                    secondLabel.Alpha = 1;
                    verificationButton.Alpha = 0;
                    secondLabel.Text = second + "s";
                    if (second < 1)
                    {
                        secondLabel.Alpha = 0;
                        verificationButton.Alpha = 1;
                    }
                    second--;
                });
            };
        }
        private void showMsgInfoAlpha()
        {
            var second = 1500;
            msgLabel.Alpha = 1f;
            var testTimer = new Timer() { Interval = 10, Enabled = true };
            testTimer.Elapsed += (object sender, System.Timers.ElapsedEventArgs e) =>
            {
                if (second < 1)
                {
                    (sender as Timer).Stop();
                }
                this.InvokeOnMainThread(() =>
                {
                    if (second < 200)
                    {
                        msgLabel.Alpha = (float) second / 200;
                    }
                    second--;
                });
            };
        }
        bool showMsgView(LoginAndRegisterRequestInfo requestInfo)
        {
            if (requestInfo.error.Length > 0)
            {
                msgLabel.Text = requestInfo.error;
                msgLabel.TextColor = UIColor.Red;
                showMsgInfoAlpha();
                return false;
            }
            else if (requestInfo.msg.Length > 0)
            {
                msgLabel.Text = requestInfo.msg;
                msgLabel.TextColor = UIColor.FromRGB(50, 110, 0);
                showMsgInfoAlpha();
            }
            return true;
        }
        private void initWrongMsg()
        {
            msgLabel.Text = "";
        }
        private bool verifyTelephone()
        {
            string telphoneString = telphoneTextField.Text;
            if (telphoneString.Length == 0)
            {
                msgLabel.Text = "手机号码必填";
                msgLabel.TextColor = UIColor.Red;
                return false;
            }
            else if (!Util.IsPhoneNo(telphoneString))
            {
                msgLabel.Text = "手机号码错误";
                msgLabel.TextColor = UIColor.Red;
                return false;
            }
            return true;
        }
    }
}